<template>
  <a-select
      :value="arrayValue"
      :disabled="disabled"
      :placeholder="placeholder"
      :getPopupContainer="getParentContainer"
      :filterOption="filterOption"
      @change="onChange"
      mode="multiple"
      optionFilterProp="children"
      allowClear>
    <a-select-option
        v-for="( item,index ) in dictOptions"
        :key="index"
        :value="item.value">
      <span class="select-option-span" :title=" item.text || item.label ">
        {{ item.text || item.label }}
      </span>
    </a-select-option>
  </a-select>
</template>

<script>
import {postAction} from "@api/manage";

export default {
  name: "GMultiSelect",
  props: {
    dictCode: String,
    value: String,
    disabled: Boolean,
    placeholder: String,
    options:Array,
    spliter: {
      type: String,
      required: false,
      default: ','
    },
    popContainer:{
      type:String,
      default:'',
      required:false
    },
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  data() {
    return {
      arrayValue: !this.value?[]:this.value.split(this.spliter),
      dictOptions: [],
    }
  },
  watch: {
    dictCode: {
      immediate: true,
      handler(){
        this.initDictData();
      }
    },
    options: function (val){
      this.setCurrentDictOptions(val);
    },
    value (val) {
      if(!val){
        this.arrayValue = []
      }else{
        this.arrayValue = this.value.split(this.spliter)
      }
    }
  },
  methods: {

    initDictData(){
      if(this.options && this.options.length > 0){
        this.dictOptions = [ ... this.options ];
      }else {
        let arr = this.dictCode.split(",");
        let params = {
          'tableName':arr[0],
          'valueField':arr[1],
          'textField':arr[2],
        };
        console.info(params);
        postAction(`/common/selectOptions`,params ).then(res => {
          if (res.success) {
            this.dictOptions = res.result.map(item => ({value: item.value, label: item.text}))
          } else {
            console.error('getDictItems error: : ', res)
            this.dictOptions = []
          }
        })
      }
    },

    getParentContainer(node) {
      if(!this.popContainer){
        return node.parentNode;
      }else {
        return document.querySelector(this.popContainer);
      }
    },

    filterOption(input,option) {
      let text = option.componentOptions.children[0].children[0].text.toLowerCase();
      return text.indexOf(input.toLowerCase()) >= 0;
    },

    onChange (selectedValue) {
      this.$emit('change',selectedValue.join(this.spliter));
    },

    setCurrentDictOptions(dictOptions){
      this.dictOptions = dictOptions;
    },
  }
}
</script>

<style scoped>
.ant-select{
  width: 100%;
}
.ant-select .select-option-span{
  display: inline-block;
  width: 100%;
}
</style>
